package com.action;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.File;
import java.io.IOException;

@RestController
@CrossOrigin("*")
public class UploadAction {

    private String tmp="d:/tmp";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/upload")
    public String  upload(MultipartFile  file) throws IOException {
        //MultipartRequest

        //得到原来的文件名  xxxx.jpg
        String oldFileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = oldFileName.lastIndexOf('.');
        //得到后辍名
        String extName = oldFileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //传到tmp目录
        File descFile = new File(tmp, newFileName);
        file.transferTo(descFile);

        //微信服务器识别
        String url = "https://api.weixin.qq.com/cv/ocr/bankcard?type=MODE&access_token=%s";
        String ACCESS_TOCKEN = (String) redisTemplate.boundValueOps("token").get();
        String newUrl = String.format(url,ACCESS_TOCKEN);

        //请求的url,上传的对象，返回的结果类型
        FileSystemResource fsr = new FileSystemResource(descFile);
        MultiValueMap  request = new LinkedMultiValueMap();
        request.add("file",fsr);
        String result = restTemplate.postForObject(newUrl, request, String.class);

        String number = JSONObject.parseObject(result).getString("number");


        return number;
    }
}
